package com.wn.ziroom.controller;


import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.wn.utils.*;
import com.wn.ziroom.entity.Owner;
import com.wn.ziroom.entity.Room;
import com.wn.ziroom.entity.User;
import com.wn.ziroom.service.RoomService;
import com.wn.ziroom.service.UserService;
import com.wn.ziroom.vo.RentHouseVo;
import com.wn.ziroom.vo.RoomUo;
import com.wn.ziroom.vo.SignVo;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import wiremock.org.apache.http.cookie.SetCookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangzhijia
 * @since 2023-02-23 02:27:54
 */
@Controller
@RequestMapping("/ziroom_portal/user")
public class UserController {

    private StringRedisTemplate redisTemplate;
    private RabbitTemplate rabbitTemplate;
    private UserService userService;

    @Autowired
    private RoomService roomService;

    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    /*----------登陆页面*/
    @GetMapping("/login")
    public String login() {

        return "login";

    }

    @PostMapping("/update")
    public String update(User user,HttpServletRequest request,HttpServletResponse response) {
        String token = CookieUtils.getCookie("token", request);
        User user1 = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
        user1 = userService.selectByPhoneNumber(user1.getPhone());
        user1.setBirth(user.getBirth());
        user1.setName(user.getName());
        userService.update(user1);

        redisTemplate.delete(token);
        token = JwtUtils.createToken(user1, 10 * 60 * 1000);
        //-- 2.把token放到Cookie中
        CookieUtils.setCookie("token", token, response);
        //-- 3.把token放入redis中
        redisTemplate.opsForValue().set(token, token, 20 * 60 * 1000, TimeUnit.MILLISECONDS);

        return "redirect:/ziroom_portal/user/goTouserInfo";
    }

    /*----------个人信息*/
    @GetMapping("/goTouserInfo")
    public String goTouserInfo(HttpServletRequest request, Model model) {
        /*---------------用户信息----------------------*/
        String token = CookieUtils.getCookie("token", request);
        User user = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
        user = userService.selectByPhoneNumber(user.getPhone());
        model.addAttribute("user", user);
        /*---------------用户房子信息-----------------*/
        RoomUo room=roomService.selectUserById(user.getId());
        model.addAttribute("room", room);


        return "userInfo";
    }


    /*--------注册页面-------------*/
    @GetMapping("/register")
    public String register() {

        return "register";

    }


    /*--------注册发送验证码---------*/
    @PostMapping("/message")
    @ResponseBody
    public String message(@RequestParam("phone") String phone) throws ExecutionException, InterruptedException {
        /*-----------判断手机号是否已被注册-----------*/
        User user = userService.selectByPhoneNumber(phone);
        if (Objects.nonNull(user)) {
            return "手机号已存在";
        }
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        MessageUtils.snedMessage(phone, code);

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(phone, String.valueOf(code), 60, TimeUnit.SECONDS);


        return "发送成功";

    }


    /*--------登录发送短信----------*/
    @PostMapping("/loginmessage")
    @ResponseBody
    public String loginmessage(@RequestParam("username") String username) throws ExecutionException, InterruptedException {
        /*-----------判断手机号是否已被注册-----------*/
        User user = userService.selectByUserName(username);
        if (Objects.isNull(user)) {
            return "手机号未注册,请新注册";
        }
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        MessageUtils.snedMessage(user.getPhone(), code);

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(username, String.valueOf(code), 60, TimeUnit.SECONDS);


        return "发送成功";

    }


    /*------注册--------*/
    @PostMapping("/addUser")
    public String addUser(User user, @RequestParam("verifyCode") String verifyCode, HttpSession session) {

        /*-----------查看token里验证码是否匹配----------*/
        /*-----------用户名是否存在------------*/
        User checkUser = userService.selectByUserName(user.getUsername());
        if (checkUser != null) {
            session.setAttribute("registerError", "用户名已存在");
            return "register";
        }
        System.out.println("允许注册");

        /*-----------可以注册---------------*/
        userService.userRegister(user);
        return "login";
    }


    /*-------登录---------*/
    @PostMapping("/loginUser")
    public String loginUser(User user, @RequestParam("verifyCode") String verifyCode,  //-- 接收验证码
                            HttpServletResponse response,  //-- 响应对象。用于把token返回给客户端
                            Map<String, Object> map) {


        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();

        /*检测验证码是否过期*/
        String value = opsForValue.get(user.getUsername());
        if (value == null) {
            map.put("error_msg", "验证码有效期60秒，已过期");
            return "login";
        }

        /*检查验证码是否正确*/
        if (!Objects.equals(verifyCode, value)) {
            map.put("error_msg", "验证码不正确");
            return "login";
        }

        /*登录成功后从redis中移除*/
        redisTemplate.delete("phone");
        System.out.println("登录信息" + user);
        User loginUser = userService.userByUser(user);
        if (Objects.nonNull(loginUser)) {
            loginUser.setPassword(null);


            String token = JwtUtils.createToken(loginUser, 10 * 60 * 1000);
            //-- 2.把token放到Cookie中
            CookieUtils.setCookie("token", token, response);
            //-- 3.把token放入redis中
            opsForValue.set(token, token, 20 * 60 * 1000, TimeUnit.MILLISECONDS);
            String Name = loginUser.getName();
            return "redirect:/";
        } else {
            map.put("error_msg", "登录信息错误");
            return "login";
        }

    }


    /*-------推出---------*/
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {

        String token = CookieUtils.getCookie("token", request);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("token".equals(cookie.getName())) {
                System.out.println(cookie.getValue());
                CookieUtils.setCookie("token", "null", response);
                System.out.println(cookie.getValue());
            }
        }
        return "redirect:/ziroom_portal/user/login";
    }


    @GetMapping("/goToPayRenewal")
    public String goToPayRenewal( Model model, HttpServletRequest request , RedirectAttributes attributes) {
        /*-----------拿到业主id和价格信息----------*/
        String token = CookieUtils.getCookie("token", request);
        User user = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
        user = userService.selectByPhoneNumber(user.getPhone());
        RoomUo roomUo = roomService.selectUserById(user.getId());
        /*---------拿到价格------------*/
        long l = SnowFlowUtils.getInstance().nextId();
        attributes.addAttribute("WIDout_trade_no",l);
        attributes.addAttribute("WIDtotal_amount",roomUo.getRent()*12);
        attributes.addAttribute("WIDsubject","续约");
        attributes.addAttribute("WIDbody","自如");


        return "redirect:/payRenewal";

    }

    @GetMapping("/goToPayRenting")
    public String goToPayRenting( Model model, HttpServletRequest request , RedirectAttributes attributes) {
        /*-----------拿到业主id和价格信息----------*/
        String token = CookieUtils.getCookie("token", request);
        User user = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
        user = userService.selectByPhoneNumber(user.getPhone());
        long time = user.getEndtime().getTime();
        long now = new Date().getTime();
        if ((now+2592000000L)>=time){
            user.setEndtime(null);
            user.setStarttime(null);
            Room room=roomService.selectByUserId(user.getId());
            room.setUserId(null);
            roomService.updateById(room);
            return "redirect:/ziroom_portal/user/goTouserInfo";

        }else {
            RoomUo roomUo = roomService.selectUserById(user.getId());
            /*---------拿到价格------------*/
            long l = SnowFlowUtils.getInstance().nextId();
            attributes.addAttribute("WIDout_trade_no",l);
            attributes.addAttribute("WIDtotal_amount",roomUo.getRent());
            attributes.addAttribute("WIDsubject","退租");
            attributes.addAttribute("WIDbody","自如");
            return "redirect:/goToPayRenting";

        }



    }



}

